var http = require("http");
var parse = require("url").parse;
var join = require("path").join;
var fs = require("fs");
var root = __dirname;
//console.log("root: " + root);
var server = http.createServer(function(req,res){
    //console.log("req.url:  " + req.url);
    var url = parse(req.url);
    //console.log("url=parse(req.url):  " + url);
    var path = join(root,url.pathname);
    //console.log("path = join(root,url.pathname):  " + path);

    /*————————— file transfering  ———————————*/
    /*var stream = fs.createReadStream(path);*/
    /*stream.on("data",function(trunk){
        res.write(trunk);
    });
    stream.on("end",function(){
        res.end();
    });*/
    /*stream.pipe(res);*/

    /*———————————— Error handling ——————————————————*/
    /*stream.on("error",function(err){
        res.statuscode = 500;
        res.end("Internal Server Error.");
    });*/

    fs.stat(path,function(err,stat){
        if(err){
            if("ENOENT" == err.code){
                res.statusCode = 404;
                res.end("Not Found!");
            }else {
                res.end("Internal Server Error.");
            }
        }else {
            res.setHeader("Content-Length",stat.size);
            var stream = fs.createReadStream(path);
            stream.pipe(res);
            stream.on("error",function(){
                res.statusCode = 500;
                res.end("Internal Server Error.");
            });
        }
    });
});
server.listen(8899);
